<template>
  <div class="container-box">
    <div class="table-wrap">
      <div class="filter-box">
        <el-form :inline="true" :model="query" class="demo-form-inline">
          <template v-for="(item, index) in columns.filter(d => d.isFilter)">
            <el-form-item :key="index" :label="item.title">
              <el-input v-model="query[item.key]" :placeholder="`请输入${item.title}`" />
            </el-form-item>
          </template>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="storeDialogVisible = true">新增门店</el-button>
      </div>
      <div class="table-box">
        <el-table :data="list" border stripe header-row-class-name="table-header-row">
          <template v-for="(item, index) in columns.filter(d => d.isTable)">
            <el-table-column :key="item.key" :prop="item.key" :label="item.title">
              <template slot-scope="scope">
                <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="120px">
            <template slot-scope="scope">
              <el-row class="button-row">
                <el-button size="mini" type="primary" icon="el-icon-edit-outline" circle @click="handleTableOp('edit', scope.row)" />
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="table-wrap">
      <div class="filter-box">
        <el-form :inline="true" :model="storeHouseQuery" class="demo-form-inline">
          <template v-for="(item, index) in storeHouseColums.filter(d => d.isFilter)">
            <el-form-item :key="index" :label="item.title">
              <el-input v-model="query[item.key]" :placeholder="`请输入${item.title}`" />
            </el-form-item>
          </template>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="storeHouseDialogVisible = true">新增仓库</el-button>
      </div>
      <div class="table-box">
        <el-table :data="storeHouseList" border stripe header-row-class-name="table-header-row">
          <template v-for="(item, index) in storeHouseColums.filter(d => d.isTable)">
            <el-table-column :key="index" :prop="item.key" :label="item.title">
              <template slot-scope="scope">
                <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>

    <el-dialog :title="`${storeForm.id ? '编辑' : '新增'}门店`" :visible.sync="storeDialogVisible">
      <el-form ref="storeForm" :model="storeForm" :rules="storeRules" label-width="100px">
        <template v-for="(item, index) in columns.filter(d => d.isForm)">
          <el-form-item v-if="item.key === 'store_id'" :key="index" :label="item.title" :prop="item.key">
            <el-select v-model="storeForm[item.key]" :placeholder="`请选择${item.title}`" style="width: 100%;">
              <el-option v-for="item in list" :key="item.id" :label="item.store_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="item.title" :prop="item.key">
            <el-input v-model="storeForm[item.key]" :placeholder="`请输入${item.title}`" />
          </el-form-item>
        </template>
        <div>其他配置</div>
        <el-form-item label="库存负载">
          <!-- <el-select v-model="storeForm[item.key]" :placeholder="`请选择${item.title}`" style="width: 100%;">
            <el-option v-for="item in list" :key="item.id" :label="item.store_name" :value="item.id" />
          </el-select> -->
          <el-switch
            v-model="storeForm.config.isAllowLoad"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCloseDialog('storeDialogVisible')">取 消</el-button>
        <el-button type="primary" @click="onSubmit('storeForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="storeHouseForm.id ? '编辑仓库' : '新增仓库'" :visible.sync="storeHouseDialogVisible">
      <el-form ref="storeHouseForm" :model="storeHouseForm" :rules="storeHouseRules" label-width="100px">
        <template v-for="(item, index) in storeHouseColums.filter(d => d.isForm)">
          <el-form-item v-if="item.key === 'store_id'" :key="index" :label="item.title" :prop="item.key">
            <el-select v-model="storeHouseForm[item.key]" :placeholder="`请选择${item.title}`" style="width: 100%;">
              <el-option v-for="item in list" :key="item.id" :label="item.store_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="item.title" :prop="item.key">
            <el-input v-model="storeHouseForm[item.key]" :placeholder="`请输入${item.title}`" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCloseDialog('storeHouseDialogVisible')">取 消</el-button>
        <el-button type="primary" @click="onSubmit('storeHouseForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { storeAdd, addStoreHouse } from '../../api/store'
export default {
  name: 'Store',
  data() {
    return {
      storeId: '',
      columns: [
        { title: '门店编号', key: 'store_no', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '门店名称', key: 'store_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '区域', key: 'area', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '联系方式', key: 'phone', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '详细地址', key: 'area_address', type: 'text', isFilter: false, isTable: true, isForm: true }
      ],
      // list: [],
      query: {},
      storeDialogVisible: false,
      storeForm: this.$defaultClass.getData('store'),
      storeRules: {
        // store_house_name: [{ required: true, message: '请输入仓库名称', trigger: ['change', 'blur'] }],
        // store_id: [{ required: true, message: '请选择所属门店', trigger:  ['change', 'blur'] }],
        // area_address: [{ required: true, message: '请输入地址', trigger:  ['change', 'blur'] }]
      },
      storeHouseColums: [
        { title: '仓库名称', key: 'store_house_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '所属门店', key: 'store_id', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '地址', key: 'area_address', type: 'text', isFilter: false, isTable: true, isForm: true }
      ],
      // storeHouseList: [],
      storeHouseQuery: {},
      storeHouseDialogVisible: false,
      storeHouseForm: {
        // store_house_name: '',
        // store_id: '',
        // area_address: '',
      },
      storeHouseRules: {
        store_house_name: [{ required: true, message: '请输入仓库名称', trigger: ['change', 'blur'] }],
        store_id: [{ required: true, message: '请选择所属门店', trigger: ['change', 'blur'] }],
        area_address: [{ required: true, message: '请输入地址', trigger: ['change', 'blur'] }]
      },
      dict: {}
    };
  },
  computed: {
    curStore() {
      const curStore = this.$store.getters.curStore;
      this.storeId = curStore?.id || '';
      return curStore;
    },
    list() {
      const list = this.$store.state.store.storeList.data;
      console.log('list==', list);
      const storeDict = {};
      list.forEach(d => {
        storeDict[d.id] = d;
      })
      this.dict.store = storeDict;
      return list;
    },
    storeHouseList() {
      const curStore = this.$store.getters.curStore;
      const list = this.$store.state.store.storeHouseList?.data || [];
      const curStoreHouseList = list.filter(d => d.store_id === curStore.id)
      return curStoreHouseList;
    }
  },
  watch: {
    storeHouseDialogVisible(val, oldVal) {
      this.storeHouseForm = {}
    }
  },
  created() {},
  methods: {
    // 操作按钮
    handleTableOp(type, row) {
      if (type === 'add') {
        this.$router.push({ path: `/order/${type}/0/${new Date().getTime()}` });
      }
      else if (type === 'fetch') {
        this.$router.push({ path: `/order/${type}/${row.id}/${new Date().getTime()}` });
      }
      else if (type === 'edit') {
        // console.log('this.$defaultClass==', defaultClass);
        const config = JSON.parse(row.config || '{}');
        this.storeForm = this.$json.cloneDeep(row);
        this.storeForm.config = this.$defaultClass.getData('storeConfig', config);
        console.log('this.storeForm.config==', this.storeForm.config);
        this.$set(this, 'storeForm', this.storeForm);
        this.storeDialogVisible = true;
      }
    },
    async onSubmit(type) {
      console.log('onSubmit==', type);
      if (!type) return;

      let isValid = false;
      let msg = '';
      this.$refs[type].validate(valid => {
        isValid = valid;
      })
      if (this.saving) msg = '请勿重复提交';
      if (!isValid) msg = '请检查提交内容';
      if (msg) {
        this.$message.error(msg)
        return;
      }
      this.saving = true;
      if (type === 'storeForm') {
        console.log('storeForm==', this.storeForm);
        const payload = this.$json.cloneDeep(this.storeForm)
        payload.config = JSON.stringify(payload.config);
        const { data } = await storeAdd(payload);
        console.log('addStoreHouse==', data);
        if (data && data.length) {
          if (data[0]) {
            if (!payload.id) {
              this.$store.dispatch('store/getStoreList')
              this.$store.dispatch('store/getStoreHouseList')
              this.storeDialogVisible = false;
            }
            this.$message.success(payload?.id ? '更新成功' : '添加成功')
          } else {
            this.$message.error(`添加失败: ${payload.store_no} || ${payload.store_name} 已存在`)
          }
        } else {
          this.$message.error(`异常：添加失败`)
        }
      } else if (type === 'storeHouseForm') {
        const res = await addStoreHouse(this.storeHouseForm);
        console.log('addStoreHouse==', res);
        await this.$store.dispatch('store/getStoreHouseList');
        this.storeHouseDialogVisible = false;
      }
      this.saving = false;
    },
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      if (item.key === 'store_id') {
        return this.dict.store[row[item.key]]?.store_name || row[item.key];
      }
      return row[item.key] || '';
    },
    onCloseDialog(type) {
      if (type === 'storeDialogVisible') {
        this.$refs.storeForm.resetFields();
      }
      else if (type === 'storeDialogVisible') {
        this.$refs.storeForm.resetFields();
      }
      this[type] = false;
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
  .table-wrap {
    margin-top: 40px;
    .filter-box {
      margin-bottom: 10px;
    }
    ::v-deep .table-header-row {
      color: #000;
      font-weight: bold !important;
    }
  }
}
</style>
